<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/25
 * Time: 16:02
 */

namespace Admin\Frontend\Controllers;


use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\XhException;
use Modules\Power;
use Services\Fiction;

class FictionController extends ControllerBase
{

    public static $article = [
        'actionType' => [0 => '全部', 1 => '及格', 2 => '良好', 3 => '优秀', 4 => '待审核', 5 => '已屏蔽'],
        'status'     => [0 =>'待审核', 1 => '通过', 2 => '删除', 3 => '屏蔽'],
        'articleRating' => [1 => '及格', 2 => '良好', 3 => '优秀'],
        'articleType' => [1 => '随感赏析',2 => '心情随笔', 3 => '命题作文'],
        'taskType'    => [0 => '自练', 1 => '任务'],
        'displayRange' => [0 => '不展示', 1 => '本班组展示', 2 => '本校展示', 3 =>'全平台展示']
    ];

    public static $comment = [
        'actionType' => [0 => '全部', 1 => '通过', 3 => '屏蔽', 4 => '待审核', 5 => '不通过'],
        'status'     => [0 => '待审核', 1 => '通过', 2 => '删除', 3 => '屏蔽', 4 => '', 5 => '不通过' ],
    ];


    /**
     * 文章列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180726
     */
    public function articleListAction()
    {
        $this->view->setTemplateBefore('listForm');
        if (!Power::exist('Admire_Article')) {
            return $this->sendViewError('缺少权限');
        }
        Main::showNavPosition();
        $this->view->pick('fiction/articleList');
        Assets::easyUI('js/fiction/articleList.js');
        $listButtonArr = $listSearchArr = [];

        $listSearchArr[] = ['type'=>'select', 'id'=>'list_taskType',
            'data'=> [0 => '全部', 1 => '自练', 2 => '任务'], 'default' => 0];
        $listSearchArr[] = ['type'=>'select', 'id'=>'list_status',
            'data'=> self::$article['actionType'], 'default' => 0];
        $listSearchArr[] = ['type'=>'select', 'id'=>'list_range',
            'data'=> [0 => '全部',4 => '不展示'] + self::$article['displayRange']  , 'default' => 0];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_start', 'label'=>' 时间：'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_end', 'label'=>' ~ '];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_vague', 'label'=>' 搜索： '];
        if (Power::exist('Admire_Article_Edit')) {
            $listButtonArr[] = ['id'=>'bt_list_recover', 'text'=>'恢复', 'plain'=>'true', 'icon'=>'fa-mail-reply'];
//            $listButtonArr[] = ['id'=>'bt_list_good', 'text'=>'优秀', 'plain'=>'true', 'icon'=>'fa-check-circle'];
//            $listButtonArr[] = ['id'=>'bt_list_well', 'text'=>'良好', 'plain'=>'true', 'icon'=>'fa-check-circle'];
            $listButtonArr[] = ['id'=>'bt_list_pass', 'text'=>'及格', 'plain'=>'true', 'icon'=>'fa-check-circle'];
            $listButtonArr[] = ['id'=>'bt_list_hide', 'text'=>'屏蔽', 'plain'=>'true', 'icon'=>'fa-minus-circle'];
        }
        if (Power::exist('Admire_Article_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }
        return $this->view->setVars([
            'List'  => Template::createList('List', 'Fiction_Article', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power' => ['editPower' => Power::exist('Admire_Article_Edit')]
        ]);
    }

    /**
     * 获取文章
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180726
     */
    public function getArticleAction()
    {
        try {
            if (!Power::exist('Admire_Article')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $page = $this->request->getPost('page', 'int');
            $size = $this->request->getPost('rows', 'int');
            $status = $this->request->getPost('status', 'string', 0);
            $startTime = $this->request->getPost('startTime', 'string');
            $endTime   = $this->request->getPost('endTime', 'string');
            $key = $this->request->getPost('key', 'string');
            $taskType = $this->request->getPost('taskType', 'string');
            $range    = $this->request->getPost('range', 'string');
            $conditionArr = [
                'actionType' => $status,
                'schoolId' => [0],
                'userId'   => 0
            ];
            if ($range) {
                $conditionArr['displayRange'] = $range == 4 ? 0 : $range ; //不展示
            }
            $conditionArr['startTime'] = $startTime ? strtotime($startTime) * 1000 : 0;
            $conditionArr['endTime']   = $endTime ? strtotime($endTime) *1000 : time()*1000;
            if ($key) {
                $conditionArr['content'] = $key;
            }
            if ($taskType) {
                $conditionArr['taskType'] = $taskType -1;
            }
            $data = Fiction::getArticles($page, $size, $conditionArr);
            Tool::runTimestamp($data['rows'], ['createTime','shieldTime','publishedTime']);
            Tool::runEnum($data['rows'], [
                'status' => self::$article['status'],
                'articleRating' => self::$article['articleRating'],
                'taskType' => self::$article['taskType'],
                'displayRange' => self::$article['displayRange']
            ]);
            foreach ($data['rows'] as &$row) {
                if (!in_array($row['status'], ['通过'])) {
                    $row['articleRating'] = '';
                }
                $row['oldContent'] = $row['content'];
                $row['content'] = str_replace(["\r\n", "\r", "\n"], '<br />', $row['content']);
                $row['articleTypeName'] = self::$article['articleType'][$row['articleType']];
            }
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 修改文章状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180726
     */
    public function dealArticleAction()
    {
        try {
            $ids = $this->request->getPost('ids', 'string');
            $action = $this->request->getPost('action', 'int');
            $range  = $this->request->getPost('range', 'int', 0);
            if ($action == 3 && !Power::exist('Admire_Article_Del')) {
                return $this->sendErrorResponse(403, '缺少权限');
            } elseif ($action != 3 && !Power::exist('Admire_Article_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            if (!is_array($ids)) {
                $ids = explode(',', $ids);
            }
            if (!$action || !$ids) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
//            if (in_array($action, [4, 5, 6])) {
//                return $this->sendErrorResponse(500, '展示范围必选');
//            }
            $data = Fiction::dealArticle($action, $ids, $range);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 设置文章状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180731
     */
    public function setSingleArticleStatusAction()
    {
        try {
            $id     = $this->request->getPost('id', 'string');
            $action = $this->request->getPost('action', 'int');
            if (!$action || !$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            if (!Power::exist('Admire_Article_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            Fiction::dealArticle($action, [$id]); //修改状态
            //获取数据
            $data = Fiction::getArticleDetail($id);
            $data = [$data];
            Tool::runTimestamp($data, ['publishedTime','shieldTime']);
            Tool::runEnum($data, ['status' => self::$article['status'],
                'articleRating' => self::$article['articleRating']]);
            foreach ($data as &$row) {
                if (!in_array($row['status'], ['通过'])) {
                    $row['articleRating'] = '';
                }
            }
            $data = $data[0];
            return  $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 评论列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180726
     */
    public function commentListAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        if (!Power::exist('Admire_Comment')) {
            return $this->sendViewError('缺少权限');
        }
        $this->view->pick('fiction/commentList');
        Assets::layUI();
        Assets::easyUI('js/fiction/commentList.js');
        $listButtonArr = $listSearchArr = [];
        $listSearchArr[] = ['type'=>'select', 'id'=>'list_status',
            'data'=> self::$comment['actionType'], 'default' => 0];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_start', 'label'=>' 时间：'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_end', 'label'=>' ~ '];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_vague', 'label'=>' 搜索： '];
        if (Power::exist('Admire_Comment_Edit')) {
            $listButtonArr[] = ['id'=>'bt_list_recover', 'text'=>'恢复', 'plain'=>'true', 'icon'=>'fa-mail-reply'];
            $listButtonArr[] = ['id'=>'bt_list_pass', 'text'=>'通过', 'plain'=>'true', 'icon'=>'fa-check-circle'];
            $listButtonArr[] = ['id'=>'bt_list_unPass', 'text'=>'不通过', 'plain'=>'true', 'icon'=>'fa-times-circle'];
            $listButtonArr[] = ['id'=>'bt_list_hide', 'text'=>'屏蔽', 'plain'=>'true', 'icon'=>'fa-minus-circle'];
        }
        if (Power::exist('Admire_Comment_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
        }
        return $this->view->setVars([
            'List'  => Template::createList('List', 'Fiction_Comment', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power' => ['editPower' => Power::exist('Admire_Comment_Edit')],
        ]);
    }

    /**
     * 获取评论数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180726
     */
    public function getCommentAction()
    {
        try {
            if (!Power::exist('Admire_Comment')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $page = $this->request->getPost('page', 'int');
            $size = $this->request->getPost('rows', 'int');
            $status = $this->request->getPost('status', 'string', 0);
            $startTime = $this->request->getPost('startTime', 'string');
            $endTime   = $this->request->getPost('endTime', 'string');
            $key = $this->request->getPost('key', 'string');
            $conditionArr = [
                'actionType' => $status,
                'schoolId' => [0]
            ];
            $conditionArr['startTime'] = $startTime ? strtotime($startTime) * 1000 : 0;
            $conditionArr['endTime']   = $endTime ? strtotime($endTime) *1000 : time()*1000;
            if ($key) {
                $conditionArr['content'] = $key;
            }
            $data = Fiction::getComment($page, $size, $conditionArr);
            Tool::runTimestamp($data['rows'], ['createTime','correctTime']);
            Tool::runEnum($data['rows'], ['status' => self::$comment['status']]);
            foreach ($data['rows'] as &$row) {
                $row['commentStar'] =
                    "<div class='comment-star' data-id='{$row['id']}' data-star='{$row['commentStar']}'></div>";
            }
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 改变星级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180731
     */
    public function changeStarAction()
    {
        try {
            if (!Power::exist('Admire_Comment_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $id = $this->request->getPost('id', 'string');
            $star = $this->request->getPost('star', 'int', 0);
            $data = Fiction::changeStar($id, $star);
            return $this->sendJsonResponse($data, true);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 处理评论
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180731
     */
    public function dealCommentAction()
    {
        try {
            $ids = $this->request->getPost('ids', 'string');
            $action = $this->request->getPost('action', 'int');
            if ($action == 3 && !Power::exist('Admire_Comment_Del')) {
                return $this->sendErrorResponse(403, '缺少权限');
            } elseif ($action != 3 && !Power::exist('Admire_Comment_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            if (!$ids || !$action) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $data = Fiction::dealComment($action, $ids);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 改变单个状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180731
     */
    public function setSingleCommentStatusAction()
    {
        try {
            $id = $this->request->getPost('id', 'string');
            $action = $this->request->getPost('action', 'int');
            if (!Power::exist('Admire_Comment_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            if (!$id || !$action) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            Fiction::dealComment($action, [$id]);
            $data = Fiction::getCommentDetail($id);
            $data = [$data];
            Tool::runTimestamp($data, ['createTime','correctTime']);
            Tool::runEnum($data, ['status' => self::$comment['status']]);
            foreach ($data as &$row) {
                $row['commentStar'] =
                    "<div class='comment-star' data-id='{$row['id']}' data-star='{$row['commentStar']}'></div>";
            }
            return $this->sendJsonResponse($data[0]);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }



}